<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vuedata数据代理与双向绑定原理2019/1/19</title>
    <!--好的代码像粥一样,是得用时间和精力熬的。-->
</head>
<body>
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<input type="text" id="d">
</body>
<script>
    let o = {
        data: {
            a: 1,
            b: 2,
            c: 3,
            d: '',
        },
        methods: {
            fn() {
                console.log(this.a)
            }
        }
    };
    proxy(o,'data');
    function proxy(target, prop) {
        Object.keys(target[prop]).forEach(function (item) {
            Object.defineProperty(target, item, {
                get() {
                    return target[prop][item];
                },
                set(newValue) {
                    target[prop][item] = newValue
                    update(item)
                },
            })
        })
    }
    function update (id) {
        if (id === 'd') {
            document.getElementById(id).value = o[id]
        } else {
            document.getElementById(id).innerText = o[id]
        }
    }
    document.getElementById('d').oninput = function(e) {
        o.d = e.target.value;
        o.c = o.d;
    };
</script>
</html>
